// 商铺广告
<template>
  <div class="role">
     <div class="role-content">
        <div class="role-top">
            <el-select v-model="paging.status" placeholder="请选择用户状态">
                <el-option
                v-for="item in statuslist"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
            <el-select v-model="paging.adType" placeholder="请选择用户类型">
                <el-option
                v-for="item in adTypelist"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
            <el-button type="primary" icon="el-icon-search" @click="role()">搜索</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="addEquipment()">添加</el-button>
        </div>
        <!--内容 -->
        <el-card class="box-card">
             <el-table :data="listData" style="width: 100%"  border>
                <el-table-column  prop="id" label="广告id" sortable> </el-table-column>
                <el-table-column prop="title" label="广告标题"  > </el-table-column>
                <el-table-column prop="adType" label="广告类型"  > 
                    <template slot-scope="scope">
                        <el-tag>{{scope.row.adType|adTypes()}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column  label="广告状态"  > 
                    <template slot-scope="scope">
                        <el-tag>{{scope.row.status|statuslist()}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column  label="广告图片">
                    <template slot-scope="scope">
                        <img :src="scope.row.imgUrl" alt="" style="width: 80px;height: 70px">
                    </template>
                 </el-table-column>
                <el-table-column prop="url" label="活动链接"  > </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini"  @click="handelEdit(scope.row)" class="blue">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分页 -->
        <div class="block">
        <!-- current-change当前页size-change每页条数current-page当前页数，支持 .sync 修饰符page-sizes每页显示条目个数，支持 .sync 修饰符-->
        <Paging @handle="handles" :allPages="paging"></Paging>
      </div>
        <!-- 添加编辑 -->
        <el-dialog :title='titleMap[dialogStatus]' :visible.sync="dialogFormVisible">
            <el-form :model="ruleForm" ref="ruleForm" :rules="rules">
            <el-form-item label="广告标题" prop='title' :label-width="formLabelWidth" style="margin-left:0;">
              <el-input  v-model="ruleForm.title" autocomplete="off"></el-input>
            </el-form-item>    
            <el-form-item label="广告图片"  prop='imgUrl' :label-width="formLabelWidth" style="margin-bottom: 0px;">
            <el-upload
                    class="avatar-uploader"
                    action="http://192.168.1.84:8081/upload/admin"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    v-model="ruleForm.imgUrl"
                    >
                    <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="广告类型" prop='adType' :label-width="formLabelWidth">
                <el-select v-model="ruleForm.adType" placeholder="请选择">
                    <el-option
                    v-for="item in adTypelist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="广告状态" prop='status' :label-width="formLabelWidth">
                <el-select v-model="ruleForm.status" placeholder="请选择">
                    <el-option
                    v-for="item in statuslist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="关联1" :label-width="formLabelWidth" class="relevance">
            <el-cascader ref="cascader" :options="options" :props="{ checkStrictly: true,value:'id',label:'label'}"  v-model="ruleForm.url" @change="handleChange" placeholder="关联产品"></el-cascader>
            </el-form-item>
            <el-form-item label="关联2" style="text-inline:2em"  @change="relevance"  :label-width="formLabelWidth" class="relevance">
                <el-select v-model="ruleForm.group" placeholder="请选择">
                    <el-option
                    v-for="item in group"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="affirm(ruleForm)">确 定</el-button>
            </div>
        </el-dialog>
     </div>
  </div>
</template>
<script>
import Shopadvert from'../../api/promotion/shopadvert'
import Paging from "../../components/Paging"; //分页
export default {
components: {
    Paging
  },
  data() {
    return {
        imageUrl: '',
        statuslist:[{
          value: '0',
          label: '冻结'
        },{
          value: '1',
          label: '激活'
        },{
          value: '2',
          label: '全部'
        }],
        adTypelist:[{
          value: '1',
          label: '轮播'
        },{
          value: '2',
          label: '分类精选'
        },{
          value: '3',
          label: '横幅'
        },{
          value: '4',
          label: '首页轮播下5按钮'
        },{
          value: null,
          label: '全部'
        }],
        group:[{
          value: '1',
          label: '团购列表'
        }],
        options:[],//spu树
     // 分页
      paging:{
        adType: '',
        status:"",
        currentPage: 1,//当前的默认的页数
        eachpage: 10,//默认的页码
        total: 0,//初始值共数据条
        totalPageNo: 1,
      },
      listData:[],//初始化数据
      dialogFormVisible:false,
      FormVisible: false, //弹窗口
      select:[],//选中的权限'
      data:[],
    // 弹框
     dialogStatus:"",
      titleMap: {
        addEquipment:'新增',            
        editEquipment: "编辑"            
     },
     //  输入框宽度
     formLabelWidth: '120px',
    //  输入框
     ruleForm:{
       group:"",
        adType:'',
        title:'',
        imgUrl:'',
        spuId:"",
        status:'',
        recommendType:"",
        gmtCreate:'',
        gmtUpdate:'',
        id:"",
        adId:'',
        url:""
     },
      rules:{
        title:[
           { required: true, message: '广告标题不能为空', trigger: 'blur'}
        ],
         imgUrl:[
           { required: true, message: '广告图片不能为空', trigger: 'blur'}
        ],
         adType:[
           { required: true, message: '请选择广告类型', trigger: 'blur'}
        ],
         status:[
           { required: true, message: '请选择广告状态', trigger: 'blur'}
        ]
      },
      currentPage:"",
      val: [],
    }
  },
  filters:{
    adTypes:function(value){
        switch (value) {
            case 4:value='首页轮播下5按钮'
                break;
           case 2:value='分类精选'
                break;
            case 1:value='轮播'
                break;
            case 3:value='横幅'
                break;
            case 1:value='轮播'
                break;
        }
        return value
    },
    statuslist:function(value) {
      switch (value) {
            case 0:value='冻结'
                break;
           case 1:value='激活'
                break;
            case 2:value='全部'
        }
        return value
    }
  },
  created() {
    this.role()
    this.spUcategory()
  },
  methods: {
     handleAvatarSuccess(res, file) {
        this.ruleForm.imgUrl=URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        return isJPG && isLt2M;
      },
    handleChange(val){
      console.log(typeof(val))
      if (val.length<3) {
            this.$message.error('请关联第三级类目或者商品')
         }
         this.val=val
       this.ruleForm.url=this.$refs.cascader.getCheckedNodes()[0].data.id//获取选中的节点数组
       
    },
    // 分页负值
    handles(val) {
      this.allPages = val;
      this.role();
    },
    //数据详情
      role(){
        let _this=this
        Shopadvert.recommanage(_this.paging).then(res=>{
            _this.listData=res.data.data.items
            _this.ruleForm={...res.data.data.items}
            _this.paging.currentPage=res.data.data.pageNo
            _this.paging.eachpage=res.data.data.pageSize
            _this.paging.total=res.data.data.total
            _this.paging.totalPageNo=res.data.data.totalPageNo
        })
      },
    // SPU树
    spUcategory(){
      Shopadvert.category().then(res=>{
          this.options= this.getTreeData(res.data.data)
      })
    },
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data){
      for(var i=0;i<data.length;i++){
        if(data[i].children.length<1){
          // children若为空数组，则将children设为undefined
          data[i].children=undefined;
        }else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // 删除
      handleDelete(row){
      let _this=this
      let data={
         adId:row.id,
         adType:row.adType,
      }
      _this.$confirm("此操作将永久删除, 是否继续?", "提示", {
          // 提示框
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          Shopadvert.deletes(data).then((res) => {
            _this.$message.success('恭喜你，删除成功');
             _this.role();
          });
        })
    },
    // 添加确认按钮
        affirm(ruleForm){
          let _this=this
        _this.$refs.ruleForm.validate((valid) => {
          if (valid) {
              if (_this.val.length<3) {
                _this.$message.error('请关联第三级类目或者商品')
              } else {
                 Shopadvert.addition(_this.ruleForm).then(res=>{
                if (res.data.errmsg=='成功') {
                  _this.$message.success('恭喜你，添加成功');
                }else{
                   _this.$message.error(res.data.errmsg);
                }
                 _this.dialogFormVisible = false;
                 _this.role()
            })
           Shopadvert.compile(_this.ruleForm).then(res=>{
             console.log(res)
                if (res.data.errmsg=='成功') {
                     _this.$message.success('恭喜你，更新广告成功');
                }else{
                   _this.$message.error(res.data.errmsg);
                }
                 _this.dialogFormVisible = false;
                 _this.role()
            })
              }
          } else {
           _this.$message.error('输入框不能为空！');
            return false;
          }
        });
    },
     // 添加
     addEquipment() {
        this.dialogFormVisible = true;
        this.dialogStatus = 'addEquipment';
        this.ruleForm={}
    },
     relevance(){
     this.ruleForm.url=''
    },
     // 编辑
      handelEdit(row) {
        console.log(row)
         this.dialogFormVisible = true;
         this.dialogStatus = 'editEquipment';
         this.ruleForm={...row}
          this.ruleForm.adId=row.id
         this.ruleForm.status=row.status==1?'冻结':'激活'
            if (row.url.indexOf("id")==-1){//查询相应的id
            this.ruleForm.url = "";
            }else{
              this.ruleForm.url= Number(row.url.split("=")[1]);
            }
          this.ruleForm.adType=row.adType==1?'轮播':row.adType==2?'分类精选':row.adType==3?'横幅':row.adType==4?'横幅首页轮播下5按钮':''
        },
    },
    watch: {
    // 去除错误提示
    dialogFormVisible(val){
     if (val == false) {
         this.$refs.ruleForm.clearValidate();
     }
    }
  }
}
</script>
<style scoped>
.role{
    width: 100%;
    line-height: 0px;
    overflow: hidden;
}
/* 上传 */
.relevance>>>.el-form-item__label{
padding-right: 30px;
}
.avatar-uploader/deep/.el-upload {
    border: 1px dashed #cccccc;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
 .avatar-uploader/deep/.el-icon-plus{
    width: 100px;
    height: 100px;
    line-height: 150px;
  }
  >>>.el-upload{
    width: 150px;
    height: 150px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  >>>.avatar-uploader{
      width: 150px;
      margin-bottom: 10px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
/* 添加编辑 */
.el-input{
    width: 300px;
}
.el-form/deep/.el-input__inner{
    width: 300px;
}
.el-form/deep/.el-form-item__content{
    width: 300px;
    margin-left:0 !important;
} 
>>>.el-dialog/deep/.el-dialog__header{
    width: 50px;
}
.el-form-item/deep/.el-form-item__error{
    text-indent:8rem
}
/* 分页 */
.block{
    width: 40%;
    padding-top: 20px;
}
/* 字体居中 */
.blue{
    background: #409EFF;
    color: #ffffff;
}
.el-table--enable-row-transition/deep/.el-table__body td {
   text-align: center;
}
.el-table/deep/th.is-sortable {
    cursor: pointer;
    text-align: center;
}
.el-table td, .el-table/deep/th.is-leaf {
    text-align: center;
}
/* 布局 */
.el-card/deep/.box-card{
  height: 50%;
   overflow: hidden;
}
.role-content{
    width: 96%;
    margin: auto;
    overflow: hidden;
}
.el-input{
    width: 200px;
    margin-right: 10px;
}
.role-top{
    width: 300px;
   line-height: 60px;
}
.role-top/deep/.el-select{
    margin-right: 10px;
}
.box-card{
   overflow: hidden;
}
</style>
